//
//  WBComposeViewController.swift
//  Weibo
//
//  Created by xu on 2017/3/28.
//  Copyright © 2017年 xuantong. All rights reserved.
//

import UIKit
import SVProgressHUD


class WBComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        self.view.backgroundColor = UIColor.white
    }

    
    //MARK: 设置界面
    
    private func setupUI() {
        setupNav()
       view.addSubview(composeTextView)
       view.addSubview(composeBottomView)

       composeTextView.addSubview(pictureCollectionView)
        //约束
        composeTextView.snp.makeConstraints { (make) in
        make.edges.equalTo(self.view)
        }
        
        composeBottomView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        pictureCollectionView.snp.makeConstraints { (make) in
            make.top.equalTo(self.composeTextView).offset(100)
            make.centerX.equalTo(self.composeTextView)
            make.size.equalTo(CGSize(width: ScreenWidth - 20, height: ScreenWidth - 20))

        }
        
        
        
        // 监听底部视图按钮点击回调
        
        composeBottomView.closure = {[weak self](type:WBComposeBottomViewType)->() in
            switch type {
            case .picture:
                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
                self?.switchKeyboardView()
            case .add:
                print("+")
            }
        
            
        }
        // 配图加号图片cell点击回调
        
        pictureCollectionView.colsure = {[weak self]in
            self?.selectImage()
        }
        
        
        // 注册系统通知-> 监听键盘将要改变frame
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        // 注册监听表情按钮点击通知
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonClick), name: NSNotification.Name(rawValue: EMOTICONBUTTONCLICKNOTI), object: nil)
        
        // 注册监听表情键盘的删除按钮点击通知
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonDeleteButtonClick), name: NSNotification.Name(rawValue: EMOTICONDELETEBUTTONCLICK), object: nil)
        
        
    }
    
    
    //设置navigationItem
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(cancelAction))
        
        
        //右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView:sendButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
      
        navigationItem.titleView = titleView
    }
    

    fileprivate lazy var composeTextView:WBComposeTextView = {
        
        let view = WBComposeTextView()
        view.font = UIFont.systemFont(ofSize: 16)
        view.placeholder = "谈谈您今天的心情吧!!!"
        //设置textview 滚动方向
        view.alwaysBounceVertical = true
        view.delegate = self
        
        return view
    }()
    
    
    private lazy var titleView: UILabel = {
        let name = WBUserAccountViewModel.shared.account?.name ?? ""
        let allText = "发微博" + "\n" + name
        let range = (allText as NSString).range(of: name)
        let attr = NSMutableAttributedString(string: allText)
        attr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize:  12), NSForegroundColorAttributeName: UIColor.orange], range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textAlignment = .center
        lab.attributedText = attr
        lab.sizeToFit()
        return lab
    }()
    
    fileprivate lazy var sendButton: UIButton = {
        
        let button = UIButton()
        button.addTarget(self, action: #selector(sendAction), for: UIControlEvents.touchUpInside)

        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.setTitleColor(UIColor.white, for: UIControlState.disabled)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.disabled)
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: UIControlState.normal)
    button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: UIControlState.highlighted)
      button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: UIControlState.disabled)
        button.frame.size = CGSize(width: 50, height: 30)
        return button
    }()
    
    
    //懒加载 底部视图
    fileprivate lazy var composeBottomView :WBComposeBottomView = WBComposeBottomView()
    // 配图
    fileprivate lazy var pictureCollectionView:WBComposePictureCollectionView = WBComposePictureCollectionView()
    // 自定义表情键盘
    fileprivate lazy var emoticonKeyboardView:WBEmoticonKeyboardView = {
    
        let view = WBEmoticonKeyboardView()
        view.frame.size = CGSize(width: ScreenWidth, height: 216)
        return view
    }()
    

}



//MARK:  监听按钮点击
extension WBComposeViewController {
    
    @objc fileprivate func cancelAction(){
        composeTextView.resignFirstResponder()
        //销毁
        dismiss(animated: true, completion: nil)
    }
    
    
    @objc fileprivate func sendAction() {
        print("发送按钮点击")
        // 创建一个可变的字符串 记录最终的结果
        var allText = ""

        composeTextView.attributedText.enumerateAttributes(in: NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (dict, range, _) in
            // 代表遍历到了文本附件
            if let att = dict["NSAttachment"] as? WBTextAttachment {
                // 字符串的拼接
                allText += (att.emoticonModel?.chs ?? "")
            }else{
                // 代表是字符串
            allText += composeTextView.attributedText.attributedSubstring(from: range).string
            }
        }

        self.pictureCollectionView.imagesArray.count > 0 ? upload(status: allText) : update(status: allText)
    }
    
    
    
    @objc fileprivate func keyboardWillChangeFrame(noti:NSNotification){
        // 判断noti.userInfo是否为nil

        guard let userInfo = noti.userInfo else {
            return
        }
         // 通过key获取到frame
        let frame = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
         //更新约束
        self.composeBottomView.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(frame.origin.y - ScreenHeight)
        }
        //获取动画时长
        let duration = (userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue

        
        //设置动画
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
   
    // 监听表情键盘按钮点击
    @objc fileprivate func emoticonButtonClick(noti:NSNotification){
        //进行判断emoticonModel是否为空
        guard let emoticonModel = noti.object as? WBEmoticonModel else {
            return
        }
        
        
     
        
         // 保存点击的表情模型 保存到最新表情中
        WBEmoticonTools.shared.saveRecentModel(model: emoticonModel)
        // 刷新表情视图pageView
        emoticonKeyboardView.reloadPageViewData()
        
        //判断是什表情
        if emoticonModel.isEmoji {
            // 得到最终的字符串表情
            let code = ((emoticonModel.code ?? "") as NSString).emoji() ?? ""

           composeTextView.insertText(code)
        }else{
            
             // 记录composeTextView已有的富文本
            
            let allAttributedText = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            // 如果是图片表情
            let allPath = emoticonModel.allPath ?? ""
             // 通过路径得到image
            let image = UIImage(named:allPath,in:WBEmoticonTools.shared.emoticonsBundle,compatibleWith: nil)

            // 计算行高
            let lineHeight = composeTextView.font!.lineHeight
            
            // 创建文本附件
            let att = WBTextAttachment()
            
            att.emoticonModel = emoticonModel
             // 设置文本附件的属性
            att.image = image

            //bounds
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            // 创建一个不可变的富文本
            let attr = NSAttributedString(attachment: att)
            
            
              //获取textview的光标
            let selectedRange = composeTextView.selectedRange
            
            
            allAttributedText.replaceCharacters(in: selectedRange, with: attr)
           
    
            // 设置font属性
            allAttributedText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: allAttributedText.length))
            

            composeTextView.attributedText = allAttributedText
            //对光标重新赋值
            composeTextView.selectedRange = NSRange(location: selectedRange.location+1, length: 0)
            // 帮助系统发送系统通知 监听文字改变

         NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange,object: nil)
        
            // 帮助系统使用代理对象执行协议方法
            composeTextView.delegate?.textViewDidChange?(composeTextView)
    
        }
    }
    
    //删除按钮
    @objc fileprivate func emoticonDeleteButtonClick(){
        
        composeTextView.deleteBackward()
    }


    
}

//MARK: 访问相册的代理方法
extension WBComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    // 切换键盘
    fileprivate func switchKeyboardView(){
    
        composeTextView.inputView = (composeTextView.inputView == nil) ?emoticonKeyboardView: nil
        // 判断是否是自定义键盘
        composeBottomView.isEmoticon = composeTextView.inputView != nil
        //刷新
        composeTextView.reloadInputViews()
        //开启第一响应者
        composeTextView.becomeFirstResponder()
        

    }
    
    
    
    //打开相册
    func selectImage(){
    
    let pickerVc = UIImagePickerController()

        pickerVc.delegate = self
        self.present(pickerVc, animated: true, completion: nil)

     }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        
        guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
            return
        }
        
        
        pictureCollectionView.addImage(image: image.dealImageScale(maxWidth: 400))
        
        picker.dismiss(animated: true, completion: nil)
    }


}


//MARK: 输入框的代理方法
extension WBComposeViewController:UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView){
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.composeTextView.resignFirstResponder()
    }

    
}


//拼接请求参数
extension WBComposeViewController {
     // 发布文字微博
    // 发布文字微博
    func update(status: String){
        
        WBNetworkTools.shared.composeUpdate(status: status) { (res, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "发送失败")
            }else{
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            }
            self.cancelAction()
        }
    }
    
  
    
    // 发布图片+文字微博
 func upload(status: String){
    
    WBNetworkTools.shared.composeUpload(status:status, imageList:self.pictureCollectionView.imagesArray) { (response, error) in
        if error != nil {
            SVProgressHUD.showError(withStatus: "发送失败")
        }else{
            SVProgressHUD.showSuccess(withStatus: "发送成功")
        }
        self.cancelAction()


    }
    
    }

 }

